/**
 * Copyright(c) Allexceed Corp.
 * All rights reserved. 
 * 
 * No user or reproduction of the whole or part of this program is permitted.
 * without the express written permission of Allexceed Corp.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted
 * 
 * $Id: Utils.java,v 1.2 2010/02/10 01:25:18 ait Exp $
 *
 * @author thuctt
 * created 2009/09/19
 * Description:Utils
 *
 * $Log: Utils.java,v $
 * Revision 1.2  2010/02/10 01:25:18  ait
 * NEC_ONU�A�g�Ή� commit 2010/02/10
 *
 * Revision 1.1  2010/02/10 01:14:01  ait
 * NEC_ONU�A�g�Ή� commit 2010/02/10
 *
 *
 *
 *
 */
package swt.commons;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;

/**
 * common util
 * 
 * @author thuctt
 */
public final class Utils {

	/**
	 * plus date
	 * 
	 * @param date
	 * @param plusYear
	 * @param plusMonth
	 * @param plusDay
	 * @return date
	 */
	public static Date plusDate(Date date, int plusYear, int plusMonth,
			int plusDay) {

		if (date == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.YEAR, plusYear);
		calendar.add(Calendar.MONTH, plusMonth);
		calendar.add(Calendar.DATE, plusDay);
		return calendar.getTime();
	}

	/**
	 * convert to date object
	 * @param strDatetime
	 * @param pattern
	 * @return Date
	 */
	public static Date toDate(String strDatetime, String pattern) {
		
		Date date = null;
		try{
			DateFormat dfm = new SimpleDateFormat(pattern);
			date = dfm.parse(strDatetime);
		}catch (ParseException  e) {
			System.out.println("[ERROR]{Utils-toDate} ParseException." + e);
		}
		return date;
	}
	
	/**
	 * plus hour/minute/second to a date
	 * 
	 * @param date
	 * @param plusHour
	 * @param plusMinute
	 * @param plusSecond
	 * @return result date
	 */
	public static Date plusTime(Date date, int plusHour, int plusMinute,
			int plusSecond) {

		if (date == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR_OF_DAY, plusHour);
		calendar.add(Calendar.MINUTE, plusMinute);
		calendar.add(Calendar.SECOND, plusSecond);
		return calendar.getTime();
	}

	/**
	 * format da date
	 * 
	 * @param iDate
	 * @param pattern
	 * @return String
	 */
	public static String formatDate(Date iDate, String pattern) {

		if (iDate == null) {
			return null;
		}
		DateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.format(iDate);
	}

	/**
	 * get day of week
	 * 
	 * @param date
	 * @return day string of week
	 */
	public static String getDayOfWeek(Date date) {

		if (date == null) {
			return "";
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int idx = calendar.get(Calendar.DAY_OF_WEEK);
		switch (idx) {
		case 1:
			return "Sunday";
		case 2:
			return "Monday";
		case 3:
			return "Tuesday";
		case 4:
			return "Wednesday";
		case 5:
			return "Thursday";
		case 6:
			return "Friday";
		case 7:
			return "Saturday";
		default:
			break;
		}
		return "";
	}

	/**
	 * NVL function
	 * 
	 * @param txt
	 * @param repTxt
	 * @return String
	 */
	public static String nvl(String txt, String repTxt) {

		if (null == txt || "".equals(txt.trim())) {
			return repTxt;
		}
		return txt.trim();
	}

	/**
	 * convert to integer from a string
	 * 
	 * @param numStr
	 * @return int
	 */
	public static int toInt(String numStr) {

		if (null == numStr || "".equals(numStr.trim())) {
			return 0;
		}
		String tmp = numStr.replaceAll("\\+", "");// delete all char "+"
		return Integer.parseInt(tmp.trim());
	}

	/**
	 * check null or empty of an object
	 * 
	 * @param obj
	 * @return boolean
	 */
	public static boolean isNullEmpty(Object obj) {
		
		if (null == obj){
			return true;
		}
		
		String txt = obj.toString().replaceAll(Const.FULL_SPACE, "");
		
		if ("".equals(txt.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * add a number of char into left of input string
	 * 
	 * @param iStr
	 * @param addedChar
	 * @param totalChar
	 * @return String
	 */
	public static String addLeft(String iStr, String addedChar, int totalChar) {

		if (iStr.length() >= totalChar) {
			return iStr;
		}
		String tmp = "";
		for (int i = 0; i < totalChar - iStr.length(); i++) {
			tmp += addedChar;
		}
		return tmp + iStr;
	}

	/**
	 * trim an input string
	 * 
	 * @param txt
	 * @return String
	 */
	public static String toEmpty(Object txt) {
		
		if (isNullEmpty(txt)) {
			return "";
		}
		String str = txt.toString().trim();
		while(str.lastIndexOf(Const.FULL_SPACE) == str.length()-1
				|| str.startsWith(Const.FULL_SPACE)){
			
			if (str.startsWith(Const.FULL_SPACE)) {
				str = str.replaceFirst(Const.FULL_SPACE, "");
			}
			if (str.lastIndexOf(Const.FULL_SPACE) == str.length()-1){
				str = str.substring(0, str.length()-1);
			}
		}
		return str.trim();
	}

	/**
	 * convert String to Date in pattern format
	 * @param dateStr
	 * @param pattern
	 * @return boolean
	 */
	public static boolean isValidDate(String dateStr, String pattern){
		try{
			if (dateStr != null && dateStr.length() > 0) {
				DateFormat dateFormat = new SimpleDateFormat(pattern);
				dateFormat.setLenient(false);
				
				dateFormat.parse(dateStr);			
			}
		}catch (ParseException e){
			return false;
		}	
		return true;
	}
	
	/**
	 * check numeric
	 * @param obj
	 * @return boolean
	 */
	public static boolean isNumeric(Object obj){
		if (null == obj){
			return false;
		}
		String txt = obj.toString().replaceFirst("-", "");
		return StringUtils.isNumeric(txt);
	}
	
	public static int maxLength(Object txt){
		
		if (null == txt){
			return 0;
		}
		return toEmpty(txt.toString()).getBytes().length;
	}
	
	/**
	 * check number halfsize
	 * @param obj
	 * @return false if error, else true
	 */
	public static boolean isHalfsize(Object obj) {
		
		if (null == obj){
			return false;
		}
		String str = Utils.toEmpty(obj.toString());
		return str.getBytes().length == str.length();
	}
	
	/**
	 * check full size
	 * 
	 * @param obj
	 * @return false if error, else true
	 */
	public static boolean isFullSize(Object obj) {
		
		if (null == obj) {
			return false;
		}
		String str = Utils.toEmpty(obj);
		return str.getBytes().length == str.length() * 2;
	}
	
	/**
	 * check max length of object
	 * @param obj
	 * @param length
	 * @return false if error, else true
	 */
	public static boolean checkMaxlength(Object obj, long length) {
		
		if (null == obj){
			return true;
		}
		return obj.toString().getBytes().length <= length;
	}
	
	/**
	 * plus Date
	 * @param strDate
	 * @param plus
	 * @return
	 */
	public static String plusDate(String strDate, int plus) {
		
		if (strDate == null) {
			return null;
		}
		
		String ret = strDate + "";
		
		int strLength = ret.length();
		if (strLength == 7) {
			ret = ret + Const.DATE_SEPARATOR + "01";
		}
		
		DateFormat dateFormat = DateFormat.getDateInstance();
		try {
			Date date = dateFormat.parse(ret);
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH, plus);
			
			date = calendar.getTime();
			
			ret = dateFormat.format(date);
			
			if (strLength == 7) {
				ret = ret.substring(0, 7);
			}
			
			return ret;
			
		} catch (ParseException e) {
			e.printStackTrace();
			return strDate;
		}
		
	}
	
	/**
	 * plus Date
	 * @param strDate
	 * @param plusYear
	 * @param plusMonth
	 * @param plusDay
	 * @return
	 */
	public static String plusDate(String strDate, int plusYear, int plusMonth, int plusDay) {
		
		if (strDate == null) {
			return null;
		}
		String ret = strDate + "";
		int strLength = ret.length();
		if (strLength == 7) {
			ret = ret + Const.DATE_SEPARATOR + "01";
		}
		DateFormat dateFormat = DateFormat.getDateInstance();
		try {
			Date date = dateFormat.parse(ret);
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.YEAR, plusYear);
			calendar.add(Calendar.MONTH, plusMonth);
			if (strLength != 7) {
				calendar.add(Calendar.DATE, plusDay);
			}
			
			date = calendar.getTime();
			
			ret = dateFormat.format(date);
			
			if (strLength == 7) {
				ret = ret.substring(0, 7);
			}
			
			return ret;
			
		} catch (ParseException e) {
			e.printStackTrace();
			return strDate;
		}
	}
	
	/**
	 * compare 2 date by YYYYMM format
	 * @param date1
	 * @param date2
	 * @param equal
	 * @return
	 */
	public static boolean compareYYYYMM(String date1, String date2, boolean equal) {
		
		if (date1.length() != 7 && date1.length() != 10 //�T�C�Y����̂݃`�F�b�N
				|| date2.length() != 7 && date2.length() != 10) {
			return false;
		}
		
		date1 = date1.substring(0, 7);
		date2 = date2.substring(0, 7);
		
		date1 = date1.replaceAll(Const.DATE_SEPARATOR, "");
		date2 = date2.replaceAll(Const.DATE_SEPARATOR, "");
		
		int dateNum1 = Integer.parseInt(date1);
		int dateNum2 = Integer.parseInt(date2);
		
		if (equal == true) {
			if (dateNum1 >= dateNum2) {
				return true;
			}
			return false;
			
		}
		if (dateNum1 > dateNum2) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * compare 2 date by YYYYMMDD format
	 * @param date1
	 * @param date2
	 * @param equal
	 * @return
	 */
	public static boolean compareYYYYMMDD(String date1, String date2, boolean equal) {
		
		if (date1.length() != 7 && date1.length() != 10
				|| date2.length() != 7 && date2.length() != 10) {
			return false;
		}
		
		if (date1.length() == 7) {
			date1 = date1 + Const.DATE_SEPARATOR + "01";
		}
		if (date2.length() == 7) {
			date2 = date2 + Const.DATE_SEPARATOR + "01";
		}
		
		date1 = date1.replaceAll("\\" + Const.DATE_SEPARATOR, "");
		date2 = date2.replaceAll("\\" + Const.DATE_SEPARATOR, "");
		
		int dateNum1 = Integer.parseInt(date1);
		int dateNum2 = Integer.parseInt(date2);
		
		if (equal == true) {
			if (dateNum1 >= dateNum2) {
				return true;
			}
			return false;
			
		}
		if (dateNum1 > dateNum2) {
			return true;
		}
		return false;
	}

	/**
	 * add double quotation
	 * @param txt
	 * @return String
	 */
	public static String addDoubleQuotations(String txt) {

		return Const.DOUBLE_QUOTATION + txt + Const.DOUBLE_QUOTATION;
	}
	
	/**
	 * add double quotation
	 * @param txt
	 * @param flg 
	 * @return String
	 */
	public static String addDoubleQuotations(String txt, boolean flg) {

		if (!flg){
			return txt;
		}
		return addDoubleQuotations(txt);
	}
	
	/**
	 * add double quotation
	 * @param num
	 * @param flg 
	 * @return String
	 */
	public static String addDoubleQuotations(int num, boolean flg) {

		if (!flg){
			return Integer.toString(num);
		}
		return addDoubleQuotations(Integer.toString(num));
	}

	/**
	 * format text of a textbox as pattern YYYY/MM/DD
	 * 
	 * @param txt
	 * @return String
	 */
	public static String formatYYYYMMDD(String txt){
		String textDt = txt.replaceAll("\\" + Const.DATE_SEPARATOR, "");
		int limit = textDt.length();
		if (limit < 6){
			return txt;
		}
		Date aDate = null;
		if (limit == 6) {// ddMMyy
			aDate = Utils.toDate(textDt, Const.DATE_FORMAT_DDMMYY);
			
		} else if (limit == 8) {// ddMMyyyy
			aDate = Utils.toDate(textDt, Const.DATE_FORMAT_DDMMYYYY);
			
		} else {
			return txt;
		}
		
		if (null == aDate){
			return txt;
		}
		
		return formatDate(aDate, Const.DATE_FORMAT);
	}
	
	/**
	 * format text of a textbox as pattern YYYY/MM
	 * 
	 * @param txt
	 * @return String
	 */
	public static String formatYYYYMM(String txt){
		
		int limit = txt.length();
		if (limit < 4){
			return txt;
		}
		
		Date aDate = null;
		
		if (limit == 4) {// YYMM
			aDate = Utils.toDate(txt, "yyMM");
			
		} else if (limit == 6) {// YYYYMM
			aDate = Utils.toDate(txt, "yyyyMM");
			
		} else {
			return txt;
		}
		
		if (null == aDate){
			return txt;
		}
		
		String retTxt = txt.substring(0, 4) + Const.DATE_SEPARATOR + txt.substring(4);
		return retTxt.substring(0, 7);
	}
	
	/**
	 * isNormalChars
	 * @param argStr
	 * @return boolean
	 */
	public static boolean isNormalChars(String argStr) {
		
		String txt = toEmpty(argStr);
		
		return txt.matches("^[a-zA-Z0-9-_]+$");
	}

	/**
	 * create NULL items string, string start with COMMA, 
	 * but not ended with COMMA
	 *  
	 * @param numItems
	 * @return String
	 */
	public static String createNULLItemsString(int numItems) {
		
		String str = "";
		for (int i = 0; i < numItems; i++) {
			str += Const.COMMA;
		}
		return str;
	}
	
	/**
	 * sort File by specified pattern 
	 * <p>0:sort all file name + external</p> 
	 * <p>1:sort just file name</p> 
	 * <p>3:sort just external</p> 
	 * 
	 * @param list
	 * @param pattern 
	 */
	public static void sortFile(ArrayList list, int pattern){
		
		if (pattern == 1){//sort all file name + external
			Collections.sort(list, new Comparator() {
		        public int compare(Object obj1, Object obj2) {
		        	String txt1 = (String)obj1;
		        	String txt2 = (String)obj2;
		            
		            return txt1.compareTo(txt2);
		        }
		    });
			
		}else if (pattern == 2){//sort just file name
			Collections.sort(list, new Comparator() {
		        public int compare(Object obj1, Object obj2) {
		        	String txt1 = (String)obj1;
		        	String txt2 = (String)obj2;
		        	String ext1 = txt1.substring(0, txt1.lastIndexOf(Const.DOT));
		            String ext2 = txt2.substring(0, txt2.lastIndexOf(Const.DOT));
		            
		            return ext1.compareTo(ext2);
		        }
		    });
			
		}else if (pattern == 3){//sort just external
			Collections.sort(list, new Comparator() {
		        public int compare(Object obj1, Object obj2) {
		        	String txt1 = (String)obj1;
		        	String txt2 = (String)obj2;
		        	String ext1 = txt1.substring(txt1.lastIndexOf(Const.DOT) + 1);
		            String ext2 = txt2.substring(txt2.lastIndexOf(Const.DOT) + 1);
		            
		            return ext1.compareTo(ext2);
		        }
		    });
		}
	}
	
	/**
	 * get client IP address 
	 * @return String
	 * @throws UnknownHostException 
	 */
	public static String getIpAddress() throws UnknownHostException {
		
		InetAddress addr = InetAddress.getLocalHost(); 
		// Get IP Address 
		return addr.getHostAddress(); 
	}
	
	/**
	 * get client IP address 
	 * @return String
	 * @throws UnknownHostException 
	 */
	public static String getHostName() throws UnknownHostException {
		
		InetAddress addr = InetAddress.getLocalHost(); 
		// Get hostname 
		return addr.getHostName(); 
	}
	
	public static int errorMsgBox(String msg) {
		MessageBox msgbox = new MessageBox(Display.getCurrent().getActiveShell(),SWT.ICON_ERROR | SWT.OK);
		ResourceUtil resourceUtil = ResourceUtil.getInstance();
		String language = resourceUtil.getProperty(Const.KEY_LANGUAGE);
		if (language.equals(Const.LANGUAGE_EN)) {
			msgbox.setText("Error");
		}
		else if (language.equals(Const.LANGUAGE_VN)) {
			msgbox.setText("Lỗi");
		}
		msgbox.setMessage(msg);
		return msgbox.open();
	}
	
	public static int infoMsgBox(String msg) {
		MessageBox msgbox = new MessageBox(Display.getCurrent().getActiveShell(),SWT.ICON_INFORMATION | SWT.OK);
		ResourceUtil resourceUtil = ResourceUtil.getInstance();
		String language = resourceUtil.getProperty(Const.KEY_LANGUAGE);
		if (language.equals(Const.LANGUAGE_EN)) {
			msgbox.setText("Information");
		}
		else if (language.equals(Const.LANGUAGE_VN)) {
			msgbox.setText("Thông báo");
		}
		msgbox.setMessage(msg);
		return msgbox.open();
	}
	
	public static int warningMsgBox(String msg) {
		MessageBox msgbox = new MessageBox(Display.getCurrent().getActiveShell(),SWT.ICON_WARNING | SWT.OK);
		ResourceUtil resourceUtil = ResourceUtil.getInstance();
		String language = resourceUtil.getProperty(Const.KEY_LANGUAGE);
		if (language.equals(Const.LANGUAGE_EN)) {
			msgbox.setText("Warning");
		}
		else if (language.equals(Const.LANGUAGE_VN)) {
			msgbox.setText("Cảnh báo");
		}
		msgbox.setMessage(msg);
		return msgbox.open();
	}
	
	public static int confirmMsgBox(String msg) {
		MessageBox msgbox = new MessageBox(Display.getCurrent().getActiveShell(),SWT.ICON_QUESTION | SWT.YES | SWT.NO);
		ResourceUtil resourceUtil = ResourceUtil.getInstance();
		String language = resourceUtil.getProperty(Const.KEY_LANGUAGE);
		if (language.equals(Const.LANGUAGE_EN)) {
			msgbox.setText("Confirm");
		}
		else if (language.equals(Const.LANGUAGE_VN)) {
			msgbox.setText("Xác nhận");
		}
		msgbox.setMessage(msg);
		return msgbox.open();
	}
}
